<template>
  <div id="app">
    <MyHeader background="yellow" title="购物车案例"></MyHeader>
    <div class="main">
      <MyGoods
        v-for="obj in list"
        :key="obj.id"
        :obj="obj"
        @stateChange="stateChange"
      >
        <MyCount :num="obj.count" @changeCount="changeCount(obj.id,$event)"> </MyCount>
      </MyGoods>
    </div>
    <MyFooter
      :allState="allState"
      :allPrice="allPrice"
      :allCount="allCount"
      @allStateChange="allStateChange"
    ></MyFooter>
  </div>
</template>

<script>
import MyHeader from "./components/MyHeader.vue";
import MyGoods from "./components/MyGoods.vue";
import MyFooter from "./components/MyFooter.vue";
import MyCount from "./components/MyCount.vue";
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      list: [], // 保存商品的所有数据
    };
  },
  // 注册组件
  components: {
    MyHeader,
    MyGoods,
    MyFooter,
    MyCount,
  },
  // 生命周期
  created() {
    axios.get("http://localhost:8080/api/info").then((response) => {
      this.list = response.data;
      console.log(this.list);
    });
  },
  methods: {
    stateChange: function (id, state) {
      let obj = this.list.find((item) => item.id === id);
      obj.state = state;
    },
    allStateChange: function (state) {
      this.list.forEach((item) => (item.state = state));
    },
    changeCount: function (id, count) {
      let obj = this.list.find((item) => item.id === id);
      obj.count = count;
    },
  },
  computed: {
    allState() {
      return this.list.every((item) => item.state);
    },
    allPrice() {
      return this.list
        .filter((item) => item.state)
        .reduce((total, item) => total + item.price * item.count, 0);
    },
    allCount() {
      return this.list
        .filter((item) => item.state)
        .reduce((total, item) => total + item.count, 0);
    },
  },
};
</script>

<style scoped lang='less'>
.main {
  padding: 45px 0 50px 0;
}
</style>
